<template>
  <div class="edit-popup">
    <popup
      ref="popupRef"
      :title="popupTitle"
      :async="true"
      width="550px"
      @confirm="handleSubmit"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="120px"
        :rules="formRules"
      >
        <el-form-item label="等级级别" prop="name" >
          <el-input v-model="formData.name" placeholder="请输入等级级别" />
        </el-form-item>
        <el-form-item label="商品提成比例" prop="rate">
          <el-input-number
              v-model="formData.rate"
              :min="0"
              :max="100"
              placeholder="请输入金额"
          />
        </el-form-item>
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from "element-plus";
import {
  UserRankDetail,
  UserRankEdit,
} from "@/api/user";
import Popup from "@/components/popup/index.vue";
const emit = defineEmits(["success", "close"]);
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");
const popupTitle = computed(() => {
  return mode.value == "edit" ? "编辑等级" : "新增等级";
});
const formData = reactive({
  name: "",
  rate: "",
  id:'',
  rank_id:''
});

const formRules = {
  name: [
    {
      required: true,
      message: "请输入等级级别",
      trigger: "blur",
    },
  ],
  rate: [
    {
      required: true,
      message: "请输入提成比例",
      trigger: "blur",
    },
  ],
};

const open = (type = "add") => {
  mode.value = type;
  popupRef.value?.open();
};

const setFormData = (data: Record<any, any>) => {
  for (const key in formData) {
    if (data.info[key] != null && data.info[key] != undefined) {
      //@ts-ignore
      formData[key] = data.info[key];
    }
  }
};

const getDetail = async (row: Record<string, any>) => {
  const data = await UserRankDetail({
    rank_id: row.id,
  });
  setFormData(data);
};

const handleClose = () => {
  emit("close");
};

defineExpose({
  open,
  setFormData,
  getDetail,
});
//提交
const handleSubmit = async () => {
	formData.rank_id = formData.id
  await formRef.value?.validate();
  await UserRankEdit(formData)
  popupRef.value?.close();
  emit("success");
};
</script>
